package com.authsphere.security.token.common.codec;

import com.authsphere.security.token.common.exception.InvalidTokenExceptionException;
import org.springframework.util.StringUtils;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @program: AuthSphere
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/26 21:00
 **/
public class DefaultBase64Codec implements TokenCodec {

    private static final String DELIMITER = ":";

    @Override
    public String encode(String[] tokens) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < tokens.length; i++) {
            sb.append(URLEncoder.encode(tokens[i], StandardCharsets.UTF_8));
            if (i < tokens.length - 1) {
                sb.append(DELIMITER);
            }
        }
        String value = sb.toString();
        sb = new StringBuilder(new String(Base64.getEncoder().encode(value.getBytes())));
        while (sb.charAt(sb.length() - 1) == '=') {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    @Override
    public String[] decode(String token) {
        for (int j = 0; j < token.length() % 4; j++) {
            token = token + "=";
        }
        String tokenAsPlainText;
        try {
            tokenAsPlainText = new String(Base64.getDecoder().decode(token.getBytes()));
        } catch (IllegalArgumentException ex) {
            throw new InvalidTokenExceptionException("token was not correct encoded");
        }
        String[] tokens = StringUtils.delimitedListToStringArray(tokenAsPlainText, DELIMITER);
        for (int i = 0; i < tokens.length; i++) {
            tokens[i] = URLDecoder.decode(tokens[i], StandardCharsets.UTF_8);
        }
        return tokens;
    }
}
